package com.atguigu.lease.web.app.service.impl;

import com.atguigu.lease.model.entity.BrowsingHistory;
import com.atguigu.lease.web.app.mapper.BrowsingHistoryMapper;
import com.atguigu.lease.web.app.service.BrowsingHistoryService;
import com.atguigu.lease.web.app.vo.history.HistoryItemVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author liubo
 * @description 针对表【browsing_history(浏览历史)】的数据库操作Service实现
 * @createDate 2023-07-26 11:12:39
 */
@Service
@Slf4j
public class BrowsingHistoryServiceImpl extends ServiceImpl<BrowsingHistoryMapper, BrowsingHistory>
        implements BrowsingHistoryService {
    @Autowired
    private BrowsingHistoryMapper browsingHistoryMapper;

    @Override
    @Async//异步线程
    public void saveHistory(Long userId, Long id) {

//        //进行数据库行为（因为数据库的并发多所以会慢，花的时间较长）
//        try {
//            Thread.sleep(5000);
//            System.out.println("保存记录成功");
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
//        //因为同步请求他不执行完后面的执行不了所以这样不行
//        //需要用异步线程，分配一个子进程专门跑这个


        BrowsingHistory browsingHistory = new BrowsingHistory();
        //用户id
        browsingHistory.setUserId(userId);
        //房间id
        browsingHistory.setRoomId(id);
        //浏览的时间
        browsingHistory.setBrowseTime(new Date());





        //查询：当前记录有没有保存,不这样的话每看一个房间就会创建一条历史记录
        //对数据库内存不好，数据太多，所以查询当前记录是否保存，如果保存了修改浏览时间！！
        Long count = browsingHistoryMapper.selectCount(new LambdaQueryWrapper<BrowsingHistory>().
                //哪个用户
                eq(BrowsingHistory::getUserId, userId).
                //看了哪个房间
                eq(BrowsingHistory::getRoomId, id));
        //判断是否有当前记录
        if (count>0){
            //修改：浏览时间
            browsingHistoryMapper.update(browsingHistory,new LambdaUpdateWrapper<BrowsingHistory>()
                    .eq(BrowsingHistory::getUserId,userId)
                    .eq(BrowsingHistory::getRoomId,id));
        }else{
            //添加
            browsingHistoryMapper.insert(browsingHistory);
        }


    }

    @Override
    public IPage<HistoryItemVo> pageInfo(Page<HistoryItemVo> historyItemVoPage,Long userId) {

        return browsingHistoryMapper.pageInfo(historyItemVoPage,userId);
    }
}
























